#include <stdio.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/mman.h>


int main(int argv, char *argc[])
{
	int fd;
	int mode;
	int opt;
	char *p_file;
	char *w_str;
	
	mode = 0;
	for(; ; )
	{
		opt = getopt(argv, argc, "rw:");
		if(opt == -1)
			break;
		
		switch(opt)
		{
			case 'r':
				mode = 0;
				break;
			case 'w':
				mode = 1;
				w_str = optarg;
				break;
			default:
				break;
		}
	}
	
	//创建文件
	fd = open("./test.txt", O_RDWR|O_CREAT, 0777);
	if(fd == -1)
	{
		perror("open");
		return -1;
	}
	
	//将文件大小截断为100B
	if(ftruncate(fd, 100) == -1)
	{
		close(fd);
		perror("ftruncate");
		return -1;
	}
	
	//将文件映射到虚拟地址
	p_file = mmap(NULL, 10, PROT_EXEC|PROT_WRITE|PROT_READ, MAP_SHARED, fd, 0); 
	if(p_file == (char*)-1) 
	{
		close(fd);
		perror("mmap");
		return -1;
	}
	
	if(mode)
	{
		//往映射区域写数据
		snprintf(p_file, 100, "%s", w_str);
		msync(p_file, 100, MS_SYNC);
	}
	else
	{
		//读映射区域
		printf("%s\r\n", p_file);
	}
	
	//取消映射
	munmap(p_file, 100);
	//关闭文件
	close(fd);
	
	return 0;
}